<template>
  <div
    :style="{ backgroundImage: `url(${imageUrl}/img/bg_ps.png)` }"
    class="user-info"
  >
    <nav-bar :background="'none'" class="nav-bar-position">
      个人资料
    </nav-bar>
    <white-space />

    <ul class="list">
      <li @tap="selectPhoto" class="item">
        <div class="label">宝贝头像</div>
        <div class="value">更换头像</div>
      </li>

      <li @tap="changeName" class="item">
        <div class="label">宝贝昵称</div>
        <div class="value">{{ userInfo.nick_name }}</div>
      </li>

      <li @tap="openPopup('sex')" class="item">
        <div class="label">宝贝性别</div>
        <div class="value">{{ userInfo.sex === 1 ? "男" : "女" }}</div>
      </li>

      <li @tap="openPopup('date')" class="item">
        <div class="label">宝贝生日</div>
        <div class="value">{{ year + "." + month + "." + day }}</div>
      </li>

      <li
        @tap="
          type = 5;
          inputShow = true;
        "
        class="item"
      >
        <div class="label">真实姓名</div>
        <div class="value">{{ userInfo.name || "未填写" }}</div>
      </li>

      <li
        @tap="
          type = 6;
          inputShow = true;
        "
        class="item"
      >
        <div class="label">学校名称</div>
        <div class="value">{{ userInfo.school_name || "未填写" }}</div>
      </li>
    </ul>

    <!--    选择性别弹窗   -->
    <pop-up ref="sex" type="bottom">
      <div class="buttons">
        <div :class="sex === 1 ? 'nan' : 'nv'" @tap="sex = 1">男</div>
        <div :class="sex !== 1 ? 'nan' : 'nv'" @tap="sex = 2">女</div>
      </div>

      <div @tap="this.updateUserInfo({ type: 3, sex })" class="sure">确定</div>
    </pop-up>

    <!--        选择c出生日期弹窗   -->
    <pop-up ref="date" type="bottom">
      <picker-view
        :value="value"
        @change="bindChange"
        class="date"
        indicator-class="date-wrap"
      >
        <picker-view-column>
          <view :key="index" class="date-item" v-for="(item, index) in years"
            >{{ item }}年
          </view>
        </picker-view-column>
        <picker-view-column>
          <view :key="index" class="date-item" v-for="(item, index) in months"
            >{{ item }}月
          </view>
        </picker-view-column>
        <picker-view-column>
          <view :key="index" class="date-item" v-for="(item, index) in days"
            >{{ item }}日
          </view>
        </picker-view-column>
      </picker-view>
      <div @tap="this.updateUserInfo({ type: 4 })" class="sure">确定</div>
    </pop-up>

    <div @tap="hidden" class="input-wrap" v-show="inputShow">
      <label @tap.stop="stop" class="input">
        <input
          :focus="inputShow"
          class="left"
          placeholder="请输入..."
          type="text"
          v-model="currentValue"
        />
        <span @tap="this.updateUserInfo({ type })" class="right">确定</span>
      </label>
    </div>

    <div class="_x">
      <navigator class="link" url="/pages_user/user-private/user-private">
        服务协议
      </navigator>
      |
      <navigator class="link" url="/pages_user/use-p/use-p">
        隐私政策
      </navigator>
    </div>

    <div class="_y">
      <p>
        杭州方体语文有限公司
      </p>
      <p>
        Copyright©2019-2020
      </p>
    </div>
  </div>
</template>

<script>
  import { imageUrl } from "../../api/url.config";
  import PopUp from "../../component/pop-up/pop-up";
  import { mapActions, mapState } from "vuex";
  import { reqUpdateUserInfo } from "../../store/modules/user/actions";
  import { Toast } from "../../utils/modal";
  import { pathToBase64 } from "../../utils/base64.js";

  export default {
  name: "user-info",
  components: {
    PopUp
  },
  data() {
    const date = new Date();
    const years = [];
    const year = date.getFullYear();
    const months = [];
    const month = date.getMonth() + 1;
    const days = [];
    const day = date.getDate();
    for (let i = 1990; i <= date.getFullYear(); i++) {
      years.push(i);
    }
    for (let i = 1; i <= 12; i++) {
      months.push(i);
    }
    for (let i = 1; i <= 31; i++) {
      days.push(i);
    }

    return {
      imageUrl,
      Date: "",
      nowDay: "",
      nowYear: "",
      nowMonth: "",
      years,
      year,
      _year: "",
      months,
      month,
      _month: "",
      days,
      day,
      _day: "",
      popUp: false,
      value: [9999, month - 1, day - 1],

      type: -1,

      currentValue: "",
      sex: 1,

      inputShow: false
    };
  },
  computed: {
    ...mapState("User", ["userInfo"])
  },
  onShow() {
    this.Date = new Date();
    this.nowDay = new Date().getDate();
    this.nowMonth = new Date().getMonth() + 1;
    this.nowYear = new Date().getFullYear();

    // #ifdef  APP-PLUS
    this.$mp.page.$getAppWebview().setStyle({
      softinputNavBar: "none"
    });
    // #endif
    const { nick_name, sex, birthday } = this.userInfo;
    this.sex = sex;
    let arr = birthday != null ? birthday.split("-") : "2019-1-1".split("-");
    console.log(birthday, arr);
    this.year = arr[0];
    this.month = arr[1];
    this.day = arr[2];
    this.value = [this.year - 1990, this.month - 1, this.day - 1];
  },
  methods: {
    ...mapActions("User", ["reqUpdateUserInfo"]),
    stripScript(e) {
      const pattern = /[`~%!@$#^='?！￥…&—‘”“？*()（）{}【】：\[\]，,。.、+_\\/><]/g;
      return pattern.test(e);
    },
    changeName() {
      this.type = 2;
      this.inputShow = true;
    },
    hidden() {
      this.inputShow = false;
    },
    selectPhoto() {
      uni.chooseImage({
        count: 1,
        success: async res => {
          console.log(res);
          let path = res.tempFilePaths[0];
          this.currentValue = await pathToBase64(path);
          this.updateUserInfo({ type: 1 });
        }
      });
    },
    async updateUserInfo({ type, ...rest }) {
      const { currentValue, stripScript, Date } = this;

      switch (type) {
        case 1: // 头像
          rest = { avatar: currentValue };
          break;
        case 2: // 昵称
          if (!currentValue) {
            return Toast({
              title: "昵称不能为空"
            });
          }
          if (stripScript(currentValue)) {
            return Toast({ title: "昵称不能含有特殊字符" });
          }
          rest = { nick_name: currentValue };
          break;
        case 3: // 性别
          if (this.userInfo.sex === rest.sex) {
            return Toast({
              title: "不能指定相同的性别"
            });
          }
          break;
        case 4: // 生日
          // this.bindChange({detail:{value:this.value}});
          console.log(this.nowYear, this.nowMonth, this.nowDay);
          if (
            this._year < this.nowYear ||
            (this._year === this.nowYear && this._month < this.nowMonth) ||
            (this._year === this.nowYear &&
              this._month === this.nowMonth &&
              this._day <= this.nowDay)
          ) {
            rest = { birthday: `${this._year}-${this._month}-${this._day}` };
          } else {
            return Toast({ title: "选择的日期大于当前日期" });
          }
          break;
        case 5: // 真实姓名
          if (!currentValue) {
            return Toast({
              title: "真实姓名不能为空"
            });
          }
          if (stripScript(currentValue)) {
            return Toast({ title: "真实姓名不能含有特殊字符" });
          }
          rest = { name: currentValue };
          break;
        case 6: // 学校名称
          if (!currentValue) {
            return Toast({
              title: "学校名称不能为空"
            });
          }
          if (stripScript(currentValue)) {
            return Toast({ title: "学校名称不能含有特殊字符" });
          }
          rest = { school_name: currentValue };
          break;
      }

      await this.reqUpdateUserInfo({ type, ...rest });
      switch (type) {
        case 1: // 头像
          this.currentValue = "";
          break;
        case 2: // 昵称
          this.inputShow = false;
          this.currentValue = "";
          break;
        case 3: // 性别
          this.closePopup("sex");
          break;
        case 4: // 生日
          this.closePopup("date");
          this.day = this._day;
          this.month = this._month;
          this.year = this._year;
          break;
        case 5: // 真实姓名
          this.inputShow = false;
          this.currentValue = "";

          break;
        case 6: // 学校名称
          this.inputShow = false;
          this.currentValue = "";
          break;
      }
    },
    openPopup(type) {
      console.log(this.value);
      this.popUp = true;
      this.$refs[type].open();
    },
    closePopup(type) {
      this.popUp = false;
      this.$refs[type].close();
    },
    bindChange(e) {
      if (this.popUp) {
        const val = e.detail.value;
        this._year = this.years[val[0]];
        this._month = this.months[val[1]];
        this._day = this.days[val[2]];
      }
    },
    stop() {}
  }
};
</script>

<style lang="scss" scoped>
@import "../../uni";

.user-info {
  @include bg;
  min-height: 100vh;
  background: {
    size: 100% 100%;
  }

  .list {
    .item {
      display: flex;
      height: upx(100);
      width: upx(590);
      background: #fff;
      border-radius: upx(50);
      margin: upx(40) auto;
      line-height: upx(100);
      box-shadow: 0 upx(12) upx(40) 0 rgba(1, 160, 152, 0.54);

      .label {
        flex: 1;
        margin-left: upx(40);
        @include ft(32, #9096a3, 500);
      }

      .value {
        position: relative;
        margin-right: upx(70);
        @include ft(32, #5d6473, 500);

        &:after {
          $size: 12;
          position: absolute;
          top: 0;
          bottom: 0;
          right: upx(-25);
          margin: auto;
          content: "";
          width: upx($size);
          height: upx($size);
          border: {
            width: upx(4) upx(4) 0 0;
            style: solid;
            color: #bbbfc6;
          }
          transform: rotate(45deg);
        }
      }
    }
  }

  .buttons {
    display: flex;
    justify-content: space-around;
    margin-top: upx(130);
    padding-bottom: upx(40);

    div {
      width: upx(272);
      height: upx(80);
      border-radius: upx(40);
      border: upx(4) solid rgba(255, 204, 24, 1);
      @include ft(32, $theme-yellow, 500);
      text-align: center;
      line-height: upx(80);
    }

    .nan {
      background: linear-gradient(
        136deg,
        rgba(255, 211, 34, 1) 0%,
        rgba(255, 186, 0, 1) 100%
      );
      color: #fff;
    }

    .nv {
    }
  }

  .sure {
    padding: upx(30) 0 0;
    text-align: center;
    border-top: upx(2) solid #edf2f3;

    @include ft(32, #5d6473, 500);
  }

  .date {
    margin-top: upx(100);
    height: upx(400);
  }

  .date-item {
    text-align: center;
    line-height: upx(68);
    @include ft(36, #273c3d, 500);
  }

  .date-wrap {
    padding: upx(10) 0;
  }

  .input-wrap {
    position: absolute;
    top: 0;
    height: 100vh;
    width: 100vw;
    background: rgba(0, 0, 0, 0.3);

    .input {
      display: flex;
      align-items: center;
      width: 100vw;
      height: upx(88);
      position: fixed;
      bottom: 0;
      border: 2px solid rgba(255, 204, 24, 1);
      line-height: upx(88);

      box-sizing: border-box;

      .left {
        background: #fff;
        height: 100%;
        width: 100%;
        padding: 0 upx(28);
        box-sizing: border-box;
        @include ft(32, #273c3d, 500);
        line-height: upx(80);
      }

      .right {
        height: 100%;
        width: upx(180);
        flex-shrink: 0;
        text-align: center;
        background: $theme-yellow;
        @include ft(32, #fff, 500);
        line-height: upx(88);
      }
    }
  }

  ._x {
    display: flex;
    justify-content: space-between;
    width: upx(340);
    margin: upx(100) auto upx(30);
    font-size: upx(28);
    font-family: PingFangSC-Regular, PingFang SC, serif;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
  }

  ._y {
    font-size: upx(26);
    font-family: PingFangSC-Regular, PingFang SC, serif;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    text-align: center;
    line-height: 1.5em;
  }
}
</style>
